<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Order as OrderModel;
use think\Db;

/**
 * 样品表模型
 */
class Sample extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order_sample';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //状态
    public static $status = [
        -1 =>     '未通过',
        0 =>      '待提交',
        1 =>      '待审核',
        2 =>      '已审核',
    ];

    //进度
    public static $progress = [
        0 =>      '待生产',
        1 =>      '钣金',
        //2 =>      '钣金',
        3 =>      '喷涂',
        //4 =>      '复合',
        5 =>      '发货',
    ];

    // 表格制作
    //print 0:编辑模式 1:打印模式
    public static function fromTabale($data = [],$print = 0){

        $table_head = [['[7:1]样板加工通知单']];
        $table_data[] = [
            "<div class='td-80' style='text-align: right;'>样单时间：</div>",
            "[3:1]<input type='hidden' name='order_id' value='{$data['order_id']}'>{$data['sample_date']}",
            "<div class='td-80' style='text-align: right;'>样品编号：</div>",
            "[2:1]".self::inputToText('sample_sn',$data['sample_sn'],$print),
        ];
        $table_data[] = [
            "<div style='text-align: right;'>工程名称：</div>",
            "[3:1]".self::inputToText('engineering',$data['engineering'],$print),
            "<div style='text-align: right;'>客户名称：</div>",
            "[2:1]".self::inputToText('company',$data['company'],$print),
        ];
        $table_data[] = [
            "<div style='text-align: center;'>序号</div>",
            "<div style='text-align: center;'>品名</div>",
            "<div style='text-align: center;'>规格及材质</div>",
            "<div style='text-align: center;'>数量(件)</div>",
            "<div style='text-align: center;'>颜色/编号</div>",
            "<div style='text-align: center;'>指定涂料厂家</div>",
            "<div id='sample_note'><div style='text-align: center;float: left;margin: 7px auto;'>交货时间要求</div><a style='float: right;' class='btn btn-success' onclick=\"sample_add()\" ><i class='fa fa-plus-circle'></i></a></div>",
        ];
        foreach ($data['sample'] as $sak=>$sav){
            if(!empty($print)){
                $table_data[] = [
                    "<div style='text-align: center;'>{$sav['sort']}</div>",
                    "<div style='text-align: center;'>{$sav['name']}</div>",
                    "<div style='text-align: center;'>{$sav['spec']}</div>",
                    "<div style='text-align: center;'>{$sav['num']}</div>",
                    "<div style='text-align: center;'>{$sav['color']}</div>",
                    "<div style='text-align: center;'>{$sav['supplier']}</div>",
                    "<div style='text-align: center;'>{$sav['date']}</div>",
                ];
            }
            else{
                $table_data[] = [
                    "[0]
             <input class='form-control sample' type='text' name='sample[sort][]' value='{$sav['sort']}'>",
                    "[0]
             <input class='form-control sample' type='text' name='sample[name][]' value='{$sav['name']}'>",
                    "[0]
             <input class='form-control sample' type='text' name='sample[spec][]' value='{$sav['spec']}'>",
                    "[0]
             <input class='form-control sample' type='text' name='sample[num][]' value='{$sav['num']}'>",
                    "[0]
             <input class='form-control sample' type='text' name='sample[color][]' value='{$sav['color']}'>",
                    "[0]
             <input class='form-control sample' type='text' name='sample[supplier][]' value='{$sav['supplier']}'>",
                    "[0]
             <input class='form-control sample' style='display:inline;width: 80%;' type='text' name='sample[date][]' value='{$sav['date']}'><a class='btn btn-primary sample sample_del' onclick=\"sample_del(this)\" ><i class='fa fa-times'></i></a>",
                ];
            }

        }

        $table_data[] = [
            "<div style='text-align: right;'>内容：</div>",
            "[6:1]".self::inputToText("content",$data['content'],$print,'height: 120px;','textarea'),
        ];

        if(!empty($print)){
            foreach ($data['require'] as $rk=>$rv_arr){
                $require_table = "[7:1]<div>{$rk}：";
                foreach ($rv_arr as $rvv){
                    $require_table .= "<label class='css-input css-checkbox css-checkbox-primary css-checkbox-sm css-checkbox-rounded'>
            <input type='checkbox' name='require[{$rk}][]' value='{$rvv}' checked><span></span>{$rvv}</label>";
                }
                $require_table .= "</div>";
                $table_data[] = [$require_table];
            }
        }
        else{
            $require = config('mill_sample_require');
            foreach ($require as $rk=>$rv){
                $require_table = "[7:1]<div>{$rk}：";
                $rv_arr = explode('|||',$rv);
                foreach ($rv_arr as $rkk=>$rvv){

                    $checked = '';
                    $rvv_html = $rvv;
                    //input框
                    if(strpos($rvv,'input') !== false){
                        $val_arr = explode('input',$rvv);
                        $val = '';
                        if(!empty($data['require'][$rk])){

                            //获取多选里额外的input文本框的值
                            $val = self::otherInputValue($val_arr,$data['require'][$rk]);

                            //截取input的值
                            //开始位子
                            $len0 = mb_strlen($val_arr[0]);
                            //input值的长度=总长度-开始位子-结束位子
                            $len1 = (mb_strlen($val)-$len0-mb_strlen($val_arr[1]));
                            $val = mb_substr($val,$len0,$len1);
                            if(!empty($val))$checked = 'checked';

                        }

                        $input = "</label>";
                        $input .= self::inputToText("require_input[{$rk}][$rvv]",$val,$print,'width: 350px;display: inline;');
                        $input .= "<label class='css-input css-checkbox css-checkbox-primary css-checkbox-sm css-checkbox-rounded'>";
                        $rvv_html = str_replace("input",$input,$rvv);

                    }

                    if(!empty($data['require'][$rk]) && in_array($rvv,$data['require'][$rk]))$checked = 'checked';
                    $require_table .= "<label class='css-input css-checkbox css-checkbox-primary css-checkbox-sm css-checkbox-rounded'>
            <input type='checkbox' name='require[{$rk}][]' value='{$rvv}' {$checked}><span></span>{$rvv_html}</label>";
                }
                $require_table .= "</div>";

                $table_data[] = [$require_table];
            }
        }

        $table_data[] = [
            "<div style='text-align: right;'>样品图：</div>",
            "[6:1]".self::inputToText("image",$data['image'],$print,'height: 120px;','image'),
        ];
        $table_data[] = [
            "<div style='text-align: right;'>其他要求：</div>",
            "[6:1]".self::inputToText("note",$data['note'],$print,'height: 120px;','textarea'),
        ];

        //样品类型 0:普通 1:大样
        if(1==2){
            $table_data[] = [
                "[9:1]<div style='text-align: right;'><div style='float: left;width: 15%;'>设计部：</div></div>",
            ];
        }
        else{
            $table_data[] = [
                "<div style='text-align: right;'>业务经办人：</div>",
                "[2:1]".self::inputToText('sales',$data['sales'],$print),
                "<div style='text-align: right;'>订单量约：</div>",
                "[1:1]".self::inputToText('order_num',$data['order_num'],$print),
                "<div style='text-align: right;'>制单人：</div>",
                "[1:1]<input type='hidden' name='admin_uid' value='{$data['admin_uid']}'>{$data['admin_nickname']}",
            ];
        }

        $table_data[] = [
            "[7:1]<div style='font-weight: bold;text-align: right;' class='td-none td-top td-50 td-h-60'>
<div style='float: left;width: 12%;'>部门领导：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
<div style='float: left;width: 12%;'>董事长：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
<div style='float: left;width: 13%;'>产品部签收：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
<div style='float: left;width: 13%;'>品质部签收：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
</div>",
        ];
        $table_data[] = [
            "[7:1]<div style='font-weight: bold;    text-align: right;' class='td-none td-top td-50 td-h-60'>
<div style='float: left;width: 12%;'>时间：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
<div style='float: left;width: 12%;'>日期：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
<div style='float: left;width: 13%;'>日期：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
<div style='float: left;width: 13%;'>日期：</div>
<div style='float: left;width: 12%;'>&nbsp;</div>
</div>",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>数控责任人：</div>",
            "[2:1]",
            "<div style='text-align: right;'>钣金质检：</div>",
            "[3:1]",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>开料责任人：</div>",
            "[6:1]",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>组长：</div>",
            "[6:1]",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>焊接责任人：</div>",
            "[2:1]",
            "<div style='text-align: right;'>喷涂质检：</div>",
            "[3:1]",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>钣金责任人：</div>",
            "[6:1]",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>喷涂责任人：</div>",
            "[6:1]",
        ];
        $table_data[] = [
            "<div class='td-h-60' style='text-align: right;'>复合车间责任人：</div>",
            "[6:1]",
        ];

        $table_data[] = [
            "[7:1]<div style='text-align: center;'>备注：打√的工序必须签字，如无签字，可以拒接收。</div>",
        ];

        return ['head'=>$table_head,'data'=>$table_data];
    }

    // 打印模板
    public static function toHtml($data = []){

        //缩放比例
        $table_scaling = 1;
        $table_style = 'border="1" style="border-collapse: collapse;width: '.(21/$table_scaling).'cm;-webkit-transform: scale('.$table_scaling.');transform-origin: 0 0;"';
        $html = '<html><style>th{font-size: 18px;font-weight: bold;}td{}</style><body style="margin: 4px;">';

        //头部
        $html .= '<table '.$table_style.'><thead>
                        <tr><th colspan="7" style="font-size: 18px;font-weight: bold;"><img style="width:41px;margin-bottom: -16px;" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/avatar.jpg">'.config('web_site_title').'</th></tr>
                    ';
        $table_arr = self::fromTabale($data,1);
        foreach ($table_arr as $tk=>$tv){
            //头
            if($tk == 'head'){
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $html .= '
                            <th rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</th>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</thead>';
            }
            //体
            elseif($tk == 'data'){
                $html .= '<tbody>';
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $html .= '
                            <td rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</tbody>';
            }
        }
        $html .= '</table>';

        //js
        $html .= '
                    <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                    <script type="text/javascript">
                        jQuery.fn.rowspan = function(colIdx=0) {
                            var that;
                            return this.each(function(row) {
                                $("td:eq(" + colIdx + ")", this).filter(":visible").each(function(col) {
                                    if (that != null && $(this).html() == $(that).html()) {
                                        rowspan = $(that).attr("rowSpan");
                                        if (rowspan == undefined) {
                                            $(that).attr("rowSpan", 1);
                                            rowspan = $(that).attr("rowSpan");
                                        }
                                        rowspan = Number(rowspan) + 1;
                                        $(that).attr("rowSpan", rowspan);
                                        $(this).hide();
                                    } else {
                                        that = this;
                                    }
                                });
                                
                            
                            });
                        };
                        $(function() {
                            //要合并的列序号，后面数字是第几列
                            $(".group").rowspan(0); 
                            $(".group").rowspan(1);
                            
                            //设置td宽高
                            $(".td-80").parent("td").css("width","80px");
                            //设置td宽高
                            $(".td-h-60").parent("td").css("height","60px");
                        });
                        window.print();
                    </script>';


        return $html;
    }

    // 获取多选里额外的input文本框的值
    public static function otherInputValue($other = [],$arr = []){
        $data = '';
        foreach ($arr as $v){
            if(strpos($v,$other[0]) !== false && strpos($v,$other[0]) == 0){
                if(empty($other[1]) || strpos($v,$other[1])){
                    $data = $v;
                    break;
                }
            }
        }

        return $data;
    }
    // 样品序列化
    // 0：序列化 1：反序列化
    public static function serialize($sample = [],$type = 0){
        $data = [];

        //序列化
        if(empty($type)){
            foreach ($sample as $sk=>$sv){
                foreach ($sv as $skk=>$svv){
                    $data[$skk][$sk] = $svv;
                }
            }
        }
        //反序列化
        else{
            foreach ($sample as $sk=>$sv){
                foreach ($sv as $skk=>$svv){
                    $data[$skk][$sk] = $svv;
                }
            }
        }

        return $data;
    }

    // input框和纯文字互转
    public static function inputToText($field = '',$val = '',$print = 0,$style = '',$input = 'input',$type = 'text'){

        if(!empty($print)){
            if($type == 'hidden')return '';
            elseif ($input == 'image' && $val)return '<img src="'.get_thumb($val).'" width="100">';
            return str_replace("\r","</br>",$val);
        }

        $re = "<input style='{$style}' class='form-control' type='{$type}' name='{$field}' value='{$val}'>";
        if($input == 'textarea')$re = "<textarea style='{$style}' class='form-control' name='{$field}'>{$val}</textarea>";
        elseif($input == 'image'){
            $thumb_html = '';
            if($val){
                $thumb_html = '<div class="file-item thumbnail">
                <img data-original="'.get_file_path($val).'" src="'.get_thumb($val).'" width="100">
                <i class="fa fa-times-circle remove-picture"></i>
            </div>';
            }
            $re = '<div class="js-upload-image">
        <div id="file_list_'.$field.'" class="uploader-list">'.$thumb_html.'</div>
        <div class="clearfix"></div>
        <input type="hidden" name="'.$field.'" data-multiple="false" data-watermark=\'\' data-thumb=\'\' data-size="0" data-ext=\'\' id="'.$field.'" value="'.$val.'">
        <div id="picker_'.$field.'">上传单张图片</div>
    </div>';
        }

        return $re;
    }
}
